<template>
  <BasicModal v-bind="$attrs"
              @register="registerModal"
              :width="1000"
              :title="getTitle"
              @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" ref="formElRef">
      <template #add="{field}">
        <!--        <input  type="hidden" :name="'levels['+field+'].sort'" :value="field"/>-->
        <Button class="ml-2" v-if="Number(field) === 0" @click="batchAdd">
          添加奖级配置
        </Button>
        <Button v-if="field > 0" @click="del(field)">-</Button>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script setup lang="ts">
import {computed, ref, unref} from 'vue';
import {formSchema, dict, appendSchema} from './ticket.data';
import {useMessage} from '@/hooks/web/useMessage';
import {getTicketApi, addTicketApi, editTicketApi} from '@/api/core/ticket.api';
import {BasicModal, useModalInner} from '@/components/Modal';
import {BasicForm, FormActionType, FormSchema, useForm} from '@/components/Form';
import {Button} from '@/components/Button';
import {TicketIM} from "@/model/core/ticket.model";
import InputNumberItem from "@/layouts/default/setting/components/InputNumberItem.vue";
import {isNotEmpty} from '@/utils/is';
import {dictConversion} from "@/utils/scratch";

const n = ref(1);
const emit = defineEmits(['success', 'register']);
const {createMessage} = useMessage();
const isUpdate = ref(true);
const [registerForm, {
  resetSchema,
  resetFields,
  updateSchema,
  setFieldsValue,
  validate,
  getFieldsValue,
  appendSchemaByField,
  removeSchemaByField
}] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
});


const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  resetFields();
  resetSchema();
  appendSchemaByField(formSchema);
  setModalProps(
    {
      confirmLoading: false
    }
  );
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    const ticket = await getTicketApi(data.record.id);
    setFieldsValue({...ticket});
    batchUpdate(ticket);
    n.value=ticket.levels.length;
  } else {
    appendSchemaByField(appendSchema);
  }
});

/** 标题初始化 */
const getTitle = computed(() => (!unref(isUpdate) ? '新增票信息管理' : '编辑票信息管理'));
defineExpose({refClose})

function refClose() {
  resetSchema();
}

/** 提交按钮 */
async function handleSubmit() {
  try {
    await validate();
    let values = getFieldsValue() as TicketIM;
    values.levels = values.levels.filter(item => JSON.stringify(item) !== '{}');
    setModalProps({confirmLoading: true});
    unref(isUpdate)
      ? await editTicketApi(values).then(() => {
        closeModal();
        createMessage.success('编辑票信息管理成功！');
      })
      : await addTicketApi(values).then(() => {
        closeModal();
        createMessage.success('新增票信息管理成功！');
      });
    emit('success');
  } finally {
    setModalProps({confirmLoading: false});
  }
}


/**
 * @description: 批量添加
 */
function batchAdd() {


  appendSchemaByField(
    [
      {
        label: '奖级名称' + n.value,
        field: 'levels[' + n.value + '].name',
        component: 'Select',
        componentProps: {
          options: dict.DicBaseTicketAwardLevelNameOptions,
          showSearch: true,
          optionFilterProp: 'label',
        },
        colProps: {span: 6},
        required: true,
      },
      {
        label: '中奖金额(元)',
        field: 'levels[' + n.value + '].winMoney',
        component: 'Input',
        colProps: {span: 6},
        required: true,
      },
      {
        label: '中奖数量',
        field: 'levels[' + n.value + '].winNum',
        component: 'Input',
        colProps: {span: 6},
        required: true,
      },
      {
        label: '',
        field: 'levels[' + n.value + '].sort',
        component: 'Input',
        defaultValue: n.value,
        ifShow: false,
      },
      {
        field: `${n.value}`,
        component: 'Input',
        label: ' ',
        slot: 'add',
        colProps: {span: 6},
      },
    ],
    '',
  );
  n.value++;
}

function del(field) {
  removeSchemaByField([`levels[${field}].name`, `levels[${field}].winMoney`, `levels[${field}].winNum`, `levels[${field}].sort`, `${field}`]);
}

function batchUpdate(ticket) {
  const m = ref(0);
  const batchUpdateSchema = [];
  ticket.levels.forEach(o => {
    batchUpdateSchema.push(
      {
        label: '奖级名称',
        field: 'levels[' + m.value + '].name',
        component: 'Select',
        defaultValue: o.name,
        componentProps: {
          options: dict.DicBaseTicketAwardLevelNameOptions,
          showSearch: true,
          optionFilterProp: 'label',
        },
        colProps: {span: 6},
        required: true,
      },
      {
        label: '中奖金额(元)',
        field: 'levels[' + m.value + '].winMoney',
        component: 'Input',
        defaultValue: o.winMoney,
        colProps: {span: 6},
        required: true,
      },
      {
        label: '中奖数量',
        field: 'levels[' + m.value + '].winNum',
        component: 'Input',
        defaultValue: o.winNum,
        colProps: {span: 6},
        required: true,
      },
      {
        label: '',
        field: 'levels[' + m.value + '].sort',
        defaultValue: isNotEmpty(o.sort) ? o.sort : m.value,
        component: 'Input',
        ifShow: false
      },
      {
        field: `${m.value}`,
        component: 'Input',
        label: ' ',
        slot: 'add',
        colProps: {span: 6},
      },
    );
    m.value++;
  })
  appendSchemaByField(batchUpdateSchema);
}

</script>
